<!--
 * @Description: 墙布发货单
 *
 * @Author: Edan<Edan>
 * @Date: 2023-07-25 09:11:54
 * @FilePath: /yuxiuproweb/src/views/qb/invoice/index.vue
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="工单号" prop="workOrderNumber">
        <el-input
          v-model="queryParams.workOrderNumber"
          placeholder="请输入工单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售单号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入销售单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工艺要求" prop="technology">
        <el-select
          style="width: 100%"
          v-model="queryParams.technology"
          filterable
          clearable
          placeholder="请选择工艺要求"
          @change="handleQuery"
        >
          <el-option label="冷胶" value="0"></el-option>
          <el-option label="热胶" value="1"></el-option>
          <el-option label="先冷后热" value="3"></el-option>
          <el-option label="无工艺" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          style="width: 100%"
          v-model="queryParams.status"
          filterable
          clearable
          placeholder="请选择状态"
          @change="handleQuery"
        >
          <el-option label="包装" value="包装"></el-option>
          <el-option label="发货" value="发货"></el-option>
          <el-option label="完结" value="完结"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="最近工序" prop="process">
        <el-select
          v-model="queryParams.process"
          filterable
          clearable
          placeholder="请选择最近工序"
          @change="handleQuery"
          @clear="handleQuery"
        >
          <el-option label="空" value="0" />
          <el-option label="裁剪" value="裁剪" />
          <el-option label="复合" value="复合" />
          <el-option label="包装" value="包装" />
          <el-option label="发货" value="发货" />
          <el-option label="已发货" value="已发货" />
        </el-select>
      </el-form-item>
      <el-form-item label="物流方式" prop="deliveryMethod">
        <el-input
          v-model="queryParams.deliveryMethod"
          placeholder="请输入物流方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发货日期" prop="deliveryTimeObj">
        <el-date-picker
          align="center"
          style="width: 240px"
          v-model="deliveryTimeObj"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="型号" prop="modelNumber">
        <el-input
          v-model="queryParams.modelNumber"
          placeholder="请输入型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据类型" prop="orderTypeList">
        <el-select
          v-model="queryParams.orderTypeList"
          placeholder="请选择单据类型"
          style="width: 100%"
          @change="changeOrderType"
          multiple
          clearable
        >
          <el-option
            v-for="dict in dict.type.qb_order_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button-group style="margin-left: 10px">
          <el-button
            :type="!queryParams.accurate ? 'primary' : 'default'"
            @click="queryParams.accurate = false"
            size="mini"
            >模糊</el-button
          >
          <el-button
            :type="queryParams.accurate ? 'primary' : 'default'"
            @click="queryParams.accurate = true"
            size="mini"
            >精确</el-button
          >
        </el-button-group>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handlePrint"
          >打印</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handleDeliveryExcel"
          >导出物流</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-truck"
          size="mini"
          v-hasRole="['toorder']"
          @click="handleOver"
          >发货完成</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          v-hasRole="['toorder']"
          @click="handleAster"
          >发货弃审</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          v-hasRole="['toorder']"
          @click="handleEnd"
          >推至完结</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      ref="tableList"
      v-loading="loading"
      :data="recordList"
      @selection-change="handleSelectionChange"
      @cell-dblclick="celldblclick"
      :max-height="maxHeight"
      show-summary
      :summary-method="getSummaries"
      :span-method="objectSpanMethod"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '0px', 'font-size': '15px' }"
      border
      size="mini"
    >
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column align="center" label="ID" width="50" fixed>
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <template v-for="(i, index) in tableForm.item">
        <el-table-column
          :key="index"
          :prop="i.itemcode"
          :columnKey="i.itemcode"
          :label="i.itemname"
          :align="i.aligntype ? i.aligntype : 'center'"
          :width="!!i.width ? i.width : ''"
          :min-width="i.minwidth"
          :show-overflow-tooltip="i.overflow ? true : false"
          :sortable="i.sortable ? true : false"
          :fixed="i.fixed"
          v-if="i.displaymark ? true : false"
        >
          <template slot-scope="scope">
            <el-button
              v-if="i.itemcode == 'workOrderNumber'"
              type="text"
              @click="handleDetail(scope.row)"
            >
              <strong style="font-size: 16px">{{
                scope.row[i.itemcode]
              }}</strong>
            </el-button>
            <div v-else-if="i.itemcode == 'technology'">
              <span v-if="scope.row[i.itemcode] == 0">冷胶</span>
              <span v-else-if="scope.row[i.itemcode] == 1">热胶</span>
              <span v-else-if="scope.row[i.itemcode] == 3">先冷后热</span>
              <span v-else>无工艺</span>
            </div>
            <div
              v-else-if="
                i.itemcode == 'isUsingRebate' ||
                i.itemcode == 'isPack' ||
                i.itemcode == 'isUrgent'
              "
            >
              <span v-if="scope.row[i.itemcode] == 1">是</span>
              <span v-else>否</span>
            </div>
            <div v-else-if="i.itemcode == 'deliveryMethod'">
              <span v-if="scope.row['postageModeOfPayment'] == 0"
                >{{ scope.row[i.itemcode] }}(寄付)</span
              >
              <span v-else-if="scope.row['postageModeOfPayment'] == 1"
                >{{ scope.row[i.itemcode] }}(到付)</span
              >
              <span v-else-if="scope.row['postageModeOfPayment'] == 2"
                >{{ scope.row[i.itemcode] }}(包邮)</span
              >
            </div>
            <div v-else-if="i.itemcode == 'logisticsNumber'">
              <el-input
                v-if="scope.row.isInputVal"
                v-model="scope.row[i.itemcode]"
                size="small"
                placeholder=""
                @blur="savelogisticsNumber(scope.row, scope.$index)"
                @keyup.enter.native="
                  savelogisticsNumber(scope.row, scope.$index)
                "
              />
              <span v-else>{{ scope.row[i.itemcode] }}</span>
            </div>
            <span v-else>{{ scope.row[i.itemcode] }}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <detail-view
      v-if="detailopen.show"
      :show.sync="detailopen.show"
      v-bind="detailopen"
      @update="getList"
    ></detail-view>
    <!-- 排单 -->
    <el-dialog
      title="单据排程"
      :append-to-body="true"
      width="400px"
      :visible.sync="scheduleVisible"
      :close-on-click-modal="false"
      class="paichengDialog"
    >
      <div style="display: flex">
        <el-date-picker
          style="width: 100%; margin-right: 10px; flex: 1"
          v-model="plandate"
          type="date"
          placeholder="YYYY-MM-DD"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submitSchedule()"
          >确 定</el-button
        >
        <el-button size="small" @click="scheduleVisible = false"
          >取 消</el-button
        >
      </div>
    </el-dialog>
    <!-- 打印 -->
    <print-view
      v-if="print.show"
      :show.sync="print.show"
      v-bind="print"
    ></print-view>
  </div>
</template>

<script>
import {
  listRecord,
  addTaskOrder,
  updateTaskOrder,
  getTaskOrder,
} from "@/api/qb";
import commonMix from "@/utils/mixins/common";
import { listClient, getClient } from "@/api/mes/md/client";
import { tableList } from "./mods/tablecolums.js";
import { export_json_to_excel } from "@/components/Excel/Export2Excel.js";
import DetailView from "./mods/detail.vue";
import PrintView from "./mods/print.vue";
export default {
  mixins: [commonMix],
  dicts: ["qb_order_state"],
  name: "Record",
  components: { DetailView, PrintView },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 交易记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      detailopen: {
        show: false,
        data: null,
      },
      clientList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        orderId: null,
        clientId: null,
        clientName: null,
        cashAccount: null,
        rebateAccount: null,
        otherAccount: null,
        technology: null,
        isShortage: null,
        status: "发货",
        process: null,
        deliveryMethod: null,
        // orderType: "SA",
        orderTypeList: ["SA"],
        accurate: false,
        sortName: "clientName",
        sort: "desc",
      },
      deliveryTimeObj: this.getCreateDateTime(),
      brandList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 排单
      scheduleVisible: false,
      plandate: null,
      selRow: [],
      // 禁用今天以前的日期
      pickerOptions: {
        disabledDate(v) {
          return v.getTime() < new Date().getTime() - 86400000; //  - 86400000是否包括当天
        },
      },
      print: {
        show: false,
        type: "0",
        data: null,
      },
      //
      tableForm: tableList,
      // 记录row
      row_logisticsNumber: "",
    };
  },
  created() {
    this.getListClient();
    this.getList();
  },
  methods: {
    getListClient(clientName = "") {
      listClient({
        pageNum: 1,
        pageSize: 100,
        enableFlag: "Y",
        clientName,
        // id: "1107",
      }).then(({ rows }) => {
        this.clientList = rows;
      });
    },
    handleClientChange() {
      const { province, city, district, address, tel } = this.clientList?.find(
        (e) => e.clientId === this.form.clientId
      );
      this.form.address = `${province || ""}${city || ""}${district || ""}${
        address || ""
      }`;
      this.form.tel = tel;
    },
    // 修改
    handleDetail(row) {
      const datarow = { ...row } || null;
      this.detailopen = {
        show: true,
        data: datarow,
      };
    },
    changeOrderType(val) {
      this.queryParams.orderTypeList = val;
      // this.handleQuery();
    },
    /** 查询生产任务列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        startDeliveryTime: this.deliveryTimeObj?.[0] || null,
        endDeliveryTime: this.deliveryTimeObj?.[1] || null,
      };
      // delete params.createDateObj;
      listRecord(params).then((response) => {
        this.recordList = [
          ...this.getSpanArr(response.rows, "number", "dealRowSpan"),
        ];
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.productionTaskId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.selRow = selection;
    },

    /** 导出按钮操作 */
    handleExport() {
      if (!this.ids.length) {
        this.$message.error("请勾选要导出的发货单");
        return;
      }
      var idsArr = [];
      for (var i = 0; i < this.ids.length; i++) {
        var item = this.ids[i];
        var obj = {
          productionTaskId: item,
        };
        idsArr.push(obj);
      }
      this.downloadExcel(
        "qb/task/export",
        idsArr,
        `墙布发货单_${new Date().getTime()}.xlsx`
      );
      this.$refs.tableList.clearSelection();
    },
    // 排单
    handleSchedule() {
      if (this.selRow.length == 0) {
        this.$message.error("请勾选单据");
        return;
      }
      this.scheduleVisible = true;
      // 判断勾选的是否有计划时间
      if (this.selRow.length == 1) {
        this.selRow[0].intendedDate
          ? (this.plandate = this.selRow[0].intendedDate)
          : (this.plandate = null);
      }
    },

    //提交，修改计划时间
    async submitSchedule() {
      // const data = await this.getTaskOrderData(this.ids[0].proOrderId);
      //  修改时间保存
      let promiseList = [];
      for (var i = 0; i < this.selRow.length; i++) {
        var item = this.selRow[i];
        var that = this;
        let promise = new Promise((resolve, reject) => {
          item.intendedDate = that.dateFormats(that.plandate);
          console.log("item", item);
          updateTaskOrder(item)
            .then((res) => {
              resolve(res || "排单成功");
            })
            .catch((er) => {
              // reject("操作失败");
            });
        });
        promiseList.push(promise);
      }
      await Promise.all(promiseList)
        .then((res) => {
          console.log("等所有异步请求完成后执行", res);
          // 等所有异步请求完成后执行
          this.$modal.msgSuccess(res.msg || "排单成功");
          this.scheduleVisible = false;
        })
        .catch((er) => {})
        .finally(() => {
          this.getList();
        });
    },
    // 双击单元格事件
    celldblclick(row, column, cell, event) {
      if (column.columnKey == "logisticsNumber") {
        if (
          this.$store.getters.roles.includes("toorder") ||
          this.$store.getters.roles.includes("admin")
        ) {
          this.$set(row, "isInputVal", true);
          this.row_logisticsNumber = JSON.stringify(row.logisticsNumber);
        }
      }
    },
    savelogisticsNumber(row, rowIndex) {
      this.$set(row, "isInputVal", false);
      if (JSON.stringify(row.logisticsNumber) == this.row_logisticsNumber) {
        return;
      }
      updateTaskOrder(row)
        .then((res) => {
          this.$modal.msgSuccess(res.msg || "操作成功");
        })
        .then(() => {
          getTaskOrder(row.productionTaskId).then((resdata) => {
            if (resdata.code == 200) {
              this.recordList[rowIndex] = resdata.data;
              this.recordList = [
                ...this.getSpanArr(this.recordList, "number", "dealRowSpan"),
              ];
            }
          });
        });
    },
    // 获取数据
    async getTaskOrderData(proOrderId) {
      const { data } = await getTaskOrder(proOrderId);
      return data;
    },
    dateFormats(dataStr) {
      if (!dataStr) {
        return;
      }
      var dt = new Date(dataStr);
      var y = dt.getFullYear();
      var m = (dt.getMonth() + 1).toString().padStart(2, "0");
      var d = dt.getDate().toString().padStart(2, "0");
      var hh = dt.getHours().toString().padStart(2, "0");
      var mm = dt.getMinutes().toString().padStart(2, "0");
      var ss = dt.getSeconds().toString().padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    handlePrint() {
      if (this.selRow.length == 0) {
        this.$message.error("请勾选打印内容");
        return;
      }
      this.print = {
        show: true,
        type: "0",
        data: this.selRow,
      };
    },
    getSummaries(param) {
      const { columns, data } = param;
      var arr = ["length"];
      const sums = [];
      columns.forEach((column, index) => {
        var bor = false;
        if (
          arr.length > 0 &&
          arr.find((item) => item == column.property) != undefined
        ) {
          bor = true;
        }
        if (index === 2) {
          sums[index] = "合计";
        } else {
          const values = data.map((item) => Number(item[column.property]));
          if (!values.every((value) => isNaN(value)) && bor) {
            sums[index] = Number(
              values
                .reduce((prev, curr) => {
                  const value = Number(curr);
                  if (!isNaN(value)) {
                    return prev + curr;
                  } else {
                    return prev;
                  }
                }, 0)
                .toFixed(2)
            );
          }
        }
      });
      return sums;
    },
    getSpanArr(list, code, rowSpan) {
      let arrZero = [];
      let Datas = [];
      // 判断需要合并的行数
      for (var i = 0; i < list.length; i++) {
        var item = list[i];
        let RowSpanNum = 1;
        for (let j = i + 1; j < list.length; j++) {
          if (item[code] == list[j][code]) {
            arrZero.push(j);
            RowSpanNum++;
          } else {
            break;
          }
        }
        if (arrZero.findIndex((ele) => ele == i) != -1) {
          RowSpanNum = 0;
        }
        Datas.push({
          ...item,
          [rowSpan]: RowSpanNum,
        });
      }
      return Datas;
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // ||
      //   column.columnKey == "contacts" ||
      //   column.columnKey == "contactNumber" ||
      //   column.columnKey == "address"
      if (column.columnKey == "number" || column.columnKey == "clientName") {
        return {
          rowspan: row.dealRowSpan,
          colspan: 1,
        };
      }
    },
    handleDeliveryExcel() {
      if (this.selRow.length == 0) {
        this.$message.error("请勾选导出内容");
        return;
      }
      require.ensure([], () => {
        const formData = [
          // { name: "订单", code: "number" },
          { name: "客户", code: "clientName" },
          { name: "收件人姓名", code: "contacts" },
          { name: "收件人电话", code: "contactNumber" },
          { name: "收货详细地址", code: "address" },
          { name: "物流方式", code: "deliveryMethod" },
          { name: "运费付款方式", code: "postageWay" },
          { name: "运输性质", code: "transportNature" },
          { name: "货物名称", code: "goodsName" },
          { name: "货物件数", code: "packNumber" },
          // { name: "货物包装", code: "packGoods" },
        ];
        const tHeader = [];
        const filterVal = [];
        for (var i = 0; i < formData.length; i++) {
          var Item = formData[i];
          tHeader.push(Item.name);
          filterVal.push(Item.code);
        }
        for (var i = 0; i < this.selRow.length; i++) {
          var item = this.selRow[i];
          item.packNumber = item.packageName;
          item.address += "-订单号:" + item.number;
          item.goodsName = "墙布";
          if (item.postageModeOfPayment == 0) {
            item.postageWay = "寄付";
          } else if (item.postageModeOfPayment == 2) {
            item.postageWay = "包邮";
          } else if (item.postageModeOfPayment == 1) {
            item.postageWay = "到付";
          } else {
            item.postageWay = "";
          }
        }
        const arr = this.mergeSimilarItems(this.selRow, "number");
        // 合并相同地址,相同收货人
        const list = arr.reduce((acc, current) => {
          const index = acc.findIndex(
            (item) =>
              item.clientName == current.clientName &&
              item.address.split("-订单号:")[0] ==
                current.address.split("-订单号:")[0]
          );
          if (index >= 0) {
            acc[index].packNumber += current.packNumber;
            acc[index].address += "，" + current.number;
          } else {
            acc.push({ ...current });
          }
          return acc;
        }, []);
        const data = this.formatJson(filterVal, list);
        // return;
        export_json_to_excel(tHeader, data, "物流导出" + new Date().getTime()); //最后一个是表名字
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    // 合并件数
    mergeSimilarItems(arr, code) {
      return arr.reduce((acc, current) => {
        const existingItemIndex = acc.findIndex(
          (item) => item[code] == current[code]
        );
        if (existingItemIndex >= 0) {
          if (!!acc.length) {
            // console.log("current", current);
            // acc[existingItemIndex].packNumber += 1;
            acc[existingItemIndex].packNumber =
              acc[existingItemIndex].packNumber > current.packageName
                ? acc[existingItemIndex].packNumber
                : current.packageName;
          }
        } else {
          acc.push({ ...current });
        }
        return acc;
      }, []);
    },
    // 发货完成
    async handleOver() {
      let promiseList = [];
      let isErr = [];
      for (var i = 0; i < this.selRow.length; i++) {
        var item = this.selRow[i];
        var that = this;

        let promise = new Promise((resolve, reject) => {
          if (item.process == "发货" && item.status == "完结") {
            item.process = "已发货";

            updateTaskOrder(item)
              .then((res) => {
                resolve(res || "操作成功");
              })
              .catch((er) => {
                reject(er || "操作失败");
              });
          } else {
            // this.$message.error(item.workOrderNumber + "该工单未完结！");
            isErr.push(item.workOrderNumber);
            reject(isErr);
          }
        });
        promiseList.push(promise);
      }
      await Promise.all(promiseList)
        .then((res) => {
          // 等所有异步请求完成后执行
          this.$modal.msgSuccess(res.msg || "操作成功");
          // this.scheduleVisible = false;
        })
        .catch((er) => {
          this.$message.error(
            er || "操作失败！" + isErr.length ? isErr + "该工单未完结！" : ""
          );
        })
        .finally(() => {
          this.getList();
        });
    },
    // 弃审
    async handleAster() {
      if (this.selRow.length == 0) {
        this.$message.error("请勾选弃审单据");
        return;
      }
      let promiseList = [];
      let isErr = [];
      for (var i = 0; i < this.selRow.length; i++) {
        var item = this.selRow[i];
        var that = this;
        let promise = new Promise((resolve, reject) => {
          if (item.status == "发货" || item.status == "完结") {
            item.status = "包装";
            item.process = item.process == "发货" ? "包装" : item.process;
            updateTaskOrder(item)
              .then((res) => {
                resolve(res || "操作成功");
              })
              .catch((er) => {
                reject(er || "操作失败");
              });
          } else {
            // this.$message.error(item.workOrderNumber + "该工单未完结！");
            isErr.push(item.workOrderNumber);
            reject(isErr);
          }
        });
        promiseList.push(promise);
      }
      await Promise.all(promiseList)
        .then((res) => {
          // 等所有异步请求完成后执行
          this.$modal.msgSuccess(res.msg || "操作成功");
        })
        .catch((er) => {
          this.$message.error(
            er || "操作失败！" + isErr.length ? +isErr + "该工单已发货0！" : ""
          );
        })
        .finally(() => {
          this.getList();
        });
    },
    // 推至完结
    async handleEnd() {
      if (this.selRow.length == 0) {
        this.$message.error("请勾选需要完结的单据");
        return;
      }
      let promiseList = [];
      let isErr = [];
      for (var i = 0; i < this.selRow.length; i++) {
        var item = this.selRow[i];
        var that = this;
        let promise = new Promise((resolve, reject) => {
          if (item.status == "发货" || item.status == "完结") {
            item.status = "完结";
            item.process = "发货";
            updateTaskOrder(item)
              .then((res) => {
                resolve(res || "操作成功");
              })
              .catch((er) => {
                reject(er || "操作失败");
              });
          } else {
            // this.$message.error(item.workOrderNumber + "该工单未完结！");
            isErr.push(item.workOrderNumber);
            reject(isErr);
          }
        });
        promiseList.push(promise);
      }
      await Promise.all(promiseList)
        .then((res) => {
          // 等所有异步请求完成后执行
          this.$modal.msgSuccess(res.msg || "操作成功");
        })
        .catch((er) => {
          this.$message.error(er || "操作失败！");
        })
        .finally(() => {
          this.getList();
        });
    },
    getCreateDateTime() {
      var dateArr = [];
      var now = new Date();
      let year = now.getFullYear(); // 获取完整的年份(4位数字)
      let month = String(now.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1
      let day = String(now.getDate()).padStart(2, "0");
      let yesterday = String(now.getDate() - 1).padStart(2, "0");
      dateArr = [
        `${year}-${month}-${day} 00:00:00`,
        `${year}-${month}-${day} 23:59:59`,
      ];
      return dateArr;
    },
  },
};
</script>
